package com.own.component.token.impl;

import com.own.component.token.base.RequestTokenManager;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * DefaultCookieRequestTokenManager
 *
 * @author chenxueli
 * @date 2023-11-07 18:47:23
 */
public class DefaultCookieRequestTokenManager implements RequestTokenManager {

    private final String tokenRequestField;
    private final String tokenResponseField;

    public DefaultCookieRequestTokenManager(String tokenRequestField, String tokenResponseField) {
        this.tokenRequestField = tokenRequestField;
        this.tokenResponseField = tokenResponseField;
    }

    /**
     * 获取token
     *
     * @param request 请求内容
     * @return 登录令牌信息
     */
    @Override
    public String token(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        var token = request.getAttribute(tokenRequestField);
        if (token != null) {
            return token.toString();
        }
        return getInCookie(request.getCookies());
    }

    /**
     * 从cookie中获取token信息
     *
     * @param cookies cookie列表信息
     * @return token信息
     */
    private String getInCookie(Cookie[] cookies) {
        for (var cookie : cookies) {
            if (cookie.getName().equals(tokenRequestField)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 存入token
     *
     * @param token    登录令牌
     * @param request  请求内容
     * @param response 响应内容
     */
    @Override
    public void save(String token, HttpServletRequest request, HttpServletResponse response) {
        var cookie = new Cookie(tokenResponseField, token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
